package com.lagou.handler;

import com.lagou.rpc.RpcRequest;
import com.lagou.server.ApplicationContextProvider;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component

@ChannelHandler.Sharable
public class UserServerHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private ApplicationContextProvider applicationContextProvider;

    @Autowired
    private RegistryHandler registryHandler;

    @Value("${rpc.server.host}")
    private String rpcServerHost;

    @Value("${rpc.server.port}")
    private Integer rpcServerPort;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 判断是否符合约定，符合则调用本地方法，返回数据
        try{
            long time1 = System.nanoTime();
            RpcRequest rpcRequest = (RpcRequest)msg;

            Object targetService = applicationContextProvider.getBean(rpcRequest.getClassName());
            Method targetMethod = targetService.getClass().getDeclaredMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
            Object result = targetMethod.invoke(targetService, rpcRequest.getParameters());
            ctx.writeAndFlush(result);
            long time2 = System.nanoTime();
            registryHandler.setResponseCost(time2 - time1);
        } catch (Exception e) {
            e.printStackTrace();
            ctx.writeAndFlush("fail");
        }
    }
}
